#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <sys/select.h>

#include <string.h>

// 串口发送数据
int serial_send(int fd, const char *data, size_t len) {
    ssize_t n = write(fd, data, len);
    if(n < 0) {
        perror("write");
        return -1;
    }
    return n;
}
int main() {
    int fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);
    if (fd == -1) {
        perror("open");
        return EXIT_FAILURE;
    }

    // 禁用非阻塞模式
    fcntl(fd, F_SETFL, 0);

    // 配置串口参数
    struct termios options;
    tcgetattr(fd, &options);
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    options.c_cflag |= CS8 | CREAD | CLOCAL;
    options.c_iflag &= ~(IXON | IXOFF | IXANY);
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;
    options.c_cc[VTIME] = 10;  // 1秒超时
    options.c_cc[VMIN]  = 0;   // 立即返回
    tcsetattr(fd, TCSANOW, &options);

 // 发送数据示例
    const char *test_data = "Hello Serial!\n";
    if(serial_send(fd, test_data, strlen(test_data)) != strlen(test_data)) {
        fprintf(stderr, "Failed to send data\n");
        close(fd);
        return EXIT_FAILURE;
    }
while(1)
{
    
    // 使用select等待数据
    fd_set read_fds;
    FD_ZERO(&read_fds);
    FD_SET(fd, &read_fds);

    struct timeval timeout = {.tv_sec = 1, .tv_usec = 0};
    int ret = select(fd + 1, &read_fds, NULL, NULL, &timeout);

    if (ret > 0 && FD_ISSET(fd, &read_fds)) {
        char buf[256];
        int n = read(fd, buf, sizeof(buf));
        if (n > 0) {
            printf("Received: ");
            fwrite(buf, 1, n, stdout);
        }
    } else if (ret == 0) {
        printf("No data received\n");
    } else {
        perror("select");
    }

}
    close(fd);
    return EXIT_SUCCESS;
}